#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var connection;
var http = require('http');
var 	mysql  = require('mysql');
var sqlcn = mysql.createConnection({
	host     : 'localhost',
	user     : 'flash',
	password : 'flash',
	database : 'iw',
});
sqlcn.query("UPDATE twalk_user SET username = username", { username: "Hello" });
/* 	var reg = {
		username: 'test3',
		password: '123'
	};
	console.log(reg);
//sqlcn.query("SELECT * FROM twalk_user WHERE username ='"+ input.username +"'", function(err, rows, fields) {
sqlcn.query("SELECT * FROM twalk_user WHERE username ='"+ reg.username +"'", function(err, rows, fields) {
	if(!rows.length>0){
		sqlcn.query('INSERT INTO twalk_user SET ?', reg, function(err, result) {
			if (err) throw err;
			console.log(result.insertId);
		});
	}else{		
		console.log("error");
	}
});  */

var server = http.createServer(function(request, response) {
    console.log('- Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(44, function() {
    console.log('- Server is listening on port 44');		

});

wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  return true;
}
function login(input){
	var msg = {
		error: "false"
	};
	sqlcn.query("SELECT * FROM twalk_user WHERE username ='"+ input.username +"' AND password ='"+input.password+"'", function(err, rows, fields) {
		if(rows.length>0){
			rows[0].error="login";
			connection.uid=rows[0].uid;
			connection.sendUTF(JSON.stringify(rows[0]));
			//console.log(rows[0]);
		}else{		
			register(input);
			//connection.sendUTF(JSON.stringify(msg));
		}
	});  
/*  	sqlcn.query("INSERT INTO twalk_user (username, password) VALUE ('"+ input.username +"'	,'"+input.password+"')", function(err, rows, fields) {
		if(rows.length>0){
			rows[0].error="true";
			connection.sendUTF(JSON.stringify(rows[0]));
		}else{connection.sendUTF(JSON.stringify(msg));}				
	}); 
 	sqlcn.query("INSERT INTO twalk_user (username, password) VALUE ('"+ input.username +"'	,'"+input.password+"')", function(err, rows, fields) {
		if(rows.length>0){
			rows[0].error="true";
			connection.sendUTF(JSON.stringify(rows[0]));
		}else{connection.sendUTF(JSON.stringify(msg));}				
	});  */
}
function register(input){
 	var msg = {
		error: "error"
	};
	sqlcn.query("SELECT * FROM twalk_user WHERE username ='"+ input.username +"'", function(err, rows, fields) {
		if(!rows.length>0){
			sqlcn.query('INSERT INTO twalk_user SET ?', {username: input.username, password: input.password}, function(err, result) {
				if (err) throw err;
				//console.log(result.insertId);
				msg.error="login";
				msg.uid=result.insertId;
				var newuid = result.insertId;
				
				sqlcn.query('INSERT INTO twalk_userevent SET ?', {uid: newuid}, function(err, result) {});
				sqlcn.query('INSERT INTO twalk_pokemon SET ?', {uid: newuid}, function(err, result) {});
				login(input);
				//connection.sendUTF(JSON.stringify(msg));
			});
		}else{		
			connection.sendUTF(JSON.stringify(msg));
		}
	});  
}
function loadpokemon(input){
	var msg = {
		error: "false"
	};
 	sqlcn.query("SELECT * FROM twalk_pokemon WHERE upid ='"+ input.upid +"'", function(err, rows, fields) {
		if(rows.length>0){
			rows[0].error="true";
			connection.sendUTF(JSON.stringify(rows[0]));
		}else{connection.sendUTF(JSON.stringify(msg));}				
	}); 
}
function loadplayerinfor(input){
	var msg = {
		error: "false"
	};
	var playerinfor = input.playerinfor;
 	sqlcn.query("SELECT "+input.playerinfor+" FROM twalk_user WHERE uid='"+input.uid+"'", function(err, rows, fields) {
		if(rows.length>0){
			rows[0].error="true";
			rows[0].playerinfor=input.playerinfor;
			connection.sendUTF(JSON.stringify(rows[0]));
		}else{connection.sendUTF(JSON.stringify(msg));}				
	}); 
}

function updateplayerinfor(input){
	var msg = {
		error: "false"
	};
	//console.log("Update"+input.playerinfor);
	var playerinfor = input.playerinfor;
	
 	sqlcn.query("UPDATE twalk_user SET "+input.playerinfor+" = '"+input.playerinforvalue+"' WHERE uid='"+input.uid+"'",function(err, result){
		if(result.affectedRows>0){
			msg.error="ok"
		}
	connection.sendUTF(JSON.stringify(msg));
	});
}
function loaduserpokemon(input){
//console.log("loaduserpokemon");
	var msg = {
		error: "false"
	};
 	sqlcn.query("SELECT * FROM twalk_pokemon WHERE uid='"+input.uid+"'", function(err, rows, fields) {
		if(rows.length>0){
			connection.sendUTF(JSON.stringify(rows));
		}else{connection.sendUTF(JSON.stringify(msg));}				
	}); 

}
function loaduseritem(input){
	var msg = {
		error: "false"
	};
 	sqlcn.query("SELECT * FROM twalk_useritem WHERE uid='"+input.uid+"'", function(err, rows, fields) {
		if(rows.length>0){
			connection.sendUTF(JSON.stringify(rows));
		}else{connection.sendUTF(JSON.stringify(msg));}				
	}); 

}
function loaduserevent(input){
	var msg = {
		error: "false"
	};
 	sqlcn.query("SELECT * FROM twalk_userevent WHERE uid='"+input.uid+"'", function(err, rows, fields) {
		if(rows.length>0){
			connection.sendUTF(JSON.stringify(rows));
		}else{connection.sendUTF(JSON.stringify(msg));}				
	}); 

}
function updatepokemon(input){
	var msg = {
		error: "false"
	};
	sqlcn.query("UPDATE twalk_pokemon SET uid = '"+input.uid+"',pid = '"+input.pid+"',pmod = '"+input.pmod+"',Name = '"+input.Name+"',Status = '"+input.Status+"',Ability = '"+input.Ability+"',HP = '"+input.HP+"',CurrentHP = '"+input.CurrentHP+"',Attack = '"+input.Attack+"',Defense = '"+input.Defense+"',SpAtk = '"+input.SpAtk+"',SpDef = '"+input.SpDef+"',Speed = '"+input.Speed+"',Move1 = '"+input.Move1+"',Move2 = '"+input.Move2+"',Move3 = '"+input.Move3+"',Move4 = '"+input.Move4+"',MoveAttack = '"+input.MoveAttack+"',PVPTurn = '"+input.PVPTurn+"' WHERE upid ='"+input.upid+"'", function(err, result){
		if(result.affectedRows>0){
			msg.error="ok"
		}
	connection.sendUTF(JSON.stringify(msg));
	});
}

function inserpokemon(input){

	var msg = {
		error: "false"
	};
	sqlcn.query("INSERT INTO twalk_pokemon SET uid = '"+input.uid+"',pid = '"+input.pid+"',pmod = '"+input.pmod+"',Name = '"+input.Name+"',Status = '"+input.Status+"',Ability = '"+input.Ability+"',HP = '"+input.HP+"',CurrentHP = '"+input.CurrentHP+"',Attack = '"+input.Attack+"',Defense = '"+input.Defense+"',SpAtk = '"+input.SpAtk+"',SpDef = '"+input.SpDef+"',Speed = '"+input.Speed+"',Move1 = '"+input.Move1+"',Move2 = '"+input.Move2+"',Move3 = '"+input.Move3+"',Move4 = '"+input.Move4+"',MoveAttack = '"+input.MoveAttack+"',PVPTurn = '"+input.PVPTurn+"'", function(err, result){
	//console.log(result);
		if(result.insertId>0){
			msg.error="ok",
			msg.upid=result.insertId
			//console.log("insert");
			//console.log(msg);
			connection.sendUTF(JSON.stringify(msg));
		}
	});
}
function updateevent(input){
	var msg = {
		error: "false"
	};
	sqlcn.query("UPDATE twalk_userevent SET "+input.eventname+" = '"+input.eventnumber+"' WHERE uid ='"+input.uid+"'", function(err, result){
		if(result.affectedRows>0){
			msg.error="ok"
		}
	connection.sendUTF(JSON.stringify(msg));s
	});
}
function updateitem(input){
	var msg = {
		error: "false"
	};
	sqlcn.query("UPDATE twalk_useritem SET NumberOf ='"+input.NumberOf+"' WHERE uid ='"+input.uid+"' AND Code ='"+input.Code+"'", function(err, result){
		if(result.affectedRows>0){
			msg.error="ok"
		}
		connection.sendUTF(JSON.stringify(msg));
	});
}
function inseritem(input){
	var msg = {
		error: "false"
	};
	sqlcn.query("INSERT INTO  twalk_useritem SET uid = '"+input.uid+"', Code = '"+input.Code+"', NumberOf ='"+input.NumberOf+"'", function(err, result){
		if(result.insertId>0){
			msg.error="ok",
			msg.upid=result.insertId
		}		
		connection.sendUTF(JSON.stringify(msg));
	});
}
wsServer.on('request', function(request) {
     if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log('- Connection from origin ' + request.origin + ' rejected.');
      return;
    }

    connection = request.accept('iw-protocol', request.origin);
    //console.log('- Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {	
			//console.log(message.utf8Data);		
			var dataPack = JSON.parse(message.utf8Data);
			switch (dataPack.action){
				case "login":
					login(dataPack);					
					break;
				case "loadpokemon":
					loadpokemon(dataPack);					
					break;
				case "loadplayerinfor":
					loadplayerinfor(dataPack);					
					break;
				case "loaduserpokemon":
					loaduserpokemon(dataPack);					
					break;
				case "loaduseritem":
					loaduseritem(dataPack);					
					break;
				case "loaduserevent":
					loaduserevent(dataPack);					
					break;
				case "inserpokemon":
					inserpokemon(dataPack);					
					break;
				case "inseritem":
					inseritem(dataPack);					
					break;
				case "updatepokemon":
					updatepokemon(dataPack);					
					break;
				case "updateitem":
					updateitem(dataPack);					
					break;
				case "updateevent":
					updateevent(dataPack);					
					break;
				case "updateplayerinfor":
					updateplayerinfor(dataPack);					
					break;
					
			}
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log('Disconnect ' + connection.uid);
    });
});